package cn.iocoder.yudao.module.trade.service.order.handler;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.module.resource.api.model.timepackage.TimePackagePaySuccessEvent;
import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderItemDO;
import cn.iocoder.yudao.module.trade.dal.mysql.order.TradeOrderMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 时间包 {@link TradeOrderHandler} 实现类
 *
 * @author cai
 */
@Slf4j
@Component
public class TradeTimePackageOrderHandler implements TradeOrderHandler {

    @Resource
    private TradeOrderMapper tradeOrderMapper;

    @Override
    public void afterPayOrder(TradeOrderDO order, List<TradeOrderItemDO> orderItems) {
        final TimePackagePaySuccessEvent event = new TimePackagePaySuccessEvent(this);
        Long orderId = order.getId();
        Long userId = order.getUserId();
        event.setOrderId(orderId);
        event.setUserId(userId);
        String timePackageId = orderItems.get(0).getTimePackageId();
        event.setTimePackageId(timePackageId);
        try {
            SpringUtil.publishEvent(event);
            log.info("发送时间包支付成功Event, orderId:{}, userId:{}, timePackageId:{}", orderId, userId, timePackageId);
            tradeOrderMapper.updateById(new TradeOrderDO().setId(order.getId()).setDeliveryTime(LocalDateTimeUtil.now()));
        } catch (Exception e) {
            log.error("时间包支付成功Event处理失败, orderId:{}, userId:{}, timePackageId:{}", orderId, userId, timePackageId, e);
        }
    }

}
